package com.hxexp.weixin.mvc.faq.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.common.json.JsonUtil;
import com.hxexp.weixin.constant.CacheName;
import com.hxexp.weixin.mvc.faq.model.FAQCategory;
import com.hxexp.weixin.mvc.faq.model.FAQItem;
import com.hxexp.weixin.mvc.faq.service.FAQService;

/**
 * 帮助服务实现类
 *
 * @author li.jiang
 *
 */
@Service
public final class FAQServiceImpl implements FAQService {
    @Autowired
    private EhCacheCacheManager ehCacheManager;
    /* (non-Javadoc)
     * @see com.hxexp.weixin.mvc.help.service.HelpService#getHelpList(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<FAQCategory> getFAQList(String faqFileRealPath) throws ServiceException {
        Cache faqCache = ehCacheManager.getCache(CacheName.FAQ_INFO);
        List<FAQCategory> faqCategoryList = faqCache.get(faqFileRealPath, new ArrayList<FAQCategory>().getClass());

        if (faqCategoryList == null) {
            faqCategoryList = JsonUtil.readJsonFile2Object(new File(faqFileRealPath), new TypeReference<List<FAQCategory>>() {
            });
            faqCache.put(faqFileRealPath, faqCategoryList);
        }

        return faqCategoryList;
    }

    /* (non-Javadoc)
     * @see com.hxexp.weixin.mvc.help.service.HelpService#getHelpItems(java.lang.String, java.lang.String)
     */
    @Override
    @Cacheable(value = CacheName.FAQ_INFO, key = "#faqFileRealPath + '@' + #categoryId")
    public List<FAQItem> getFAQItems(String faqFileRealPath, String categoryId) throws ServiceException {
        List<FAQCategory> faqCategoryList = getFAQList(faqFileRealPath);
        for (FAQCategory faqCategory : faqCategoryList) {
            if (faqCategory.getCategoryId().equals(categoryId)) {
                return faqCategory.getItems();
            }
        }

        return new ArrayList<FAQItem>(0);
    }

}
